<template>
  <div class="first_chain_view">
    <!-- <Form :searchForm="propsForm" ref="formRef" @my-btn="handBtnClick"></Form>
    <Table
      ref="tableRef"
      :tableProps="tableProps"
      :tableData="tableList"
      :pageTotal="tableTotal"
      :loading="loading"
      @get-page="handPage"
      @handTableRow="handTableRow"
    ></Table> -->
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="init('reset')" @changePanel="resizeWin">
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="initParams" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品编码">
                    <el-select multiple v-model="initParams.condition.productCodeList" style="width: 100%"
                      @change="init('search')" placeholder="请选择产品编码" filterable clearable collapse-tags
                      collapse-tags-tooltip>
                      <el-option v-for="item in listCollect.productList" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="运营商">
                    <el-select v-model="initParams.condition.isp" @change="init('search')" style="width: 100%"
                      placeholder="请选择运营商" clearable>
                      <el-option v-for="item in ispEnum" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="所在地-省">
                    <el-cascader :options="twoLevelCity" @change="changeValue" v-model="cityCode" :props="{
                      checkStrictly: true,
                      value: 'dictItemCode',
                      label: 'dictItemName',
                      children: 'childrenDictItemList',
                    }" clearable></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="init('search')">查询</el-button>
                <el-button @click="init('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>
            <el-button :icon="Plus" v-permission="'PRODUCT_RECOMMENDATION:CREATE-EDIT'" type="primary" title="新增首链"
              @click="handBtnClick({ type: 'add' }, {})"></el-button>
            <el-dropdown :hide-on-click="false" style="margin: 0 10px" trigger="click">
              <el-button title="过滤表头">
                <el-icon :size="18">
                  <Grid />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-checkbox-group v-model="selectTitle" size="small" @change="checkboxChange">
                    <el-dropdown-item v-for="item in showTitle" :key="item.prop">
                      <el-checkbox :label="item.label" :value="item.prop" />
                    </el-dropdown-item>
                  </el-checkbox-group>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total" @get-page="handPage"
          :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight" :loading="pageParams.loadIng">
          <template #province="scope">
                  {{ handLocation(scope.row, {prop:'whiteListProvince'}) }} 
          </template>
          <template #city="scope">
                  {{ handLocation(scope.row, {prop:'whiteListCity'}) }} 
          </template>
          <template #handle="scope">
           
            <el-button type="primary" size="small" v-permission="'PRODUCT_RECOMMENDATION:CREATE-EDIT'" link
              @click="handTableRow({ name: '编辑' }, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" v-permission="'PRODUCT_RECOMMENDATION:DELETE'" link
              @click="handTableRow({ name: '删除' }, scope.row)">删除</el-button>
              <el-button type="primary" size="small" v-permission="'PRODUCT_RECOMMENDATION:DETAIL'" link
              @click="handTableRow({ name: '详情' }, scope.row)">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <Add ref="addRef" :infoData="infoData" @tableFlush="tableFlush('reset')" @search-edit="tableFlush('search')"></Add>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { storeToRefs } from "pinia";
import _ from "lodash";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue"
import Add from "./comp/add.vue";
import config from "./config/index.ts";
import {
  getProductCnfList,
  delCnfPeoduct,
  getCnfProductInfo,
} from "@/api/product";
import useInstance from '@/hooks/useInstance';

import { useColorStore } from "@/store/common";
import { useEnumStore } from "@/store/enumeration.ts";
import { firstChainListStore } from "./pageStore.ts";
import { useComListData } from "@/store/list.ts";

const {getProListAll,listCollect} = useComListData()
const commonStore = useColorStore()
const { ispSelectList, province } = storeToRefs(commonStore)
const { filterData } = commonStore
const { global } = useInstance();

const { tableProp } = storeToRefs(firstChainListStore());
const { ispEnum,isIsp } = storeToRefs(useEnumStore());
const provinceStore = useColorStore();
const { twoLevelCity } = storeToRefs(provinceStore);
const { searchForm, tableProps } = config;
const selectTitle = ref<any>([]);
const onlyTableRef=ref()
let propsForm = ref({ ...searchForm });
let formRef = ref();
let addRef = ref();
let tableRef = ref();
const infoData = ref({});
const cityCode = ref<any>([]);

let initParams = ref({
  pageNum: 1,
  pageSize: 20,
  condition: {
    productCodeList: [], // 请选择产品
    isp: [], // 运营商
    whiteListProvince: null,
    whiteListCity: null,
  },
  orders: ["created_time desc"],
});
const pageParams = reactive({
  loadIng: false,
  tableData: [],
  total: 0,
  tableHeight: 500,
  productList: [] as any,
});
const resizeWin = _.debounce(() => {
  const dom1 = document.querySelector(".card-1") as any;
  const dom2 = document.querySelector(".card-com") as any;

  if (dom2) {
    const height = dom2.offsetHeight - dom1.offsetHeight - 70;
    pageParams.tableHeight = height;
  }
}, 200);
const initCompPag = () => {
  tableRef.value?.initPagination();
  initParams.value.pageNum = 1;
  initParams.value.pageSize = 20;
};
const showTitle = computed(() => {
  return tableProp.value.propsList.filter((it) => it.label != "操作");
});
const checkboxChange = (val: string[]) => {
  pageParams.loadIng = true;
  // 进入的 全部为 true 没有的为false
  tableProp.value.propsList = tableProp.value.propsList.map((item: any) => {
    if (val.includes(item.prop)) {
      return {
        ...item,
        hidden: true,
      };
    } else if (item.label == "操作") {
      return {
        ...item,
        hidden: true,
      };
    } else {
      return {
        ...item,
        hidden: false,
      };
    }
  });
  pageParams.loadIng = false;
};
onMounted(() => {
  selectTitle.value = tableProp.value.propsList
    .filter((it) => it.hidden && it.label != "操作")
    .map((item) => item.prop);
  nextTick(() => {
    const dom1 = document.querySelector(".card-1") as any;
    const dom2 = document.querySelector(".card-com") as any;

    if (dom2) {
      const height = dom2.offsetHeight - dom1.offsetHeight - 70;
      pageParams.tableHeight = height;
    }
  })
  window.addEventListener("resize", resizeWin)

  init("search");
  tableRef.value?.handuseResize(70);
  getProListAll({})
});
onUnmounted(() => {
  window.removeEventListener("resize", resizeWin)
})
const handLocation = (row: any, item: any) => {
  if (item.prop == "whiteListProvince") {
    let code = row[item.prop]
    let target = province.value.filter((item: any) => item.dictItemCode == code)
    if (target.length !== 0) {
      return target[0].dictItemName ? target[0].dictItemName : "-"
    }
  } else {
    let code = row["whiteListProvince"]
    let city = row[item.prop]
    if (code) {
      let arr = filterData(1, null, code)
      if (arr.length !== 0) {
        let obj = arr[0].childrenDictItemList.find(
          (item: any) => item.dictItemCode == city
        )        
       return obj && obj.dictItemName
      }
    }
  }
}
const changeValue = (val: any) => {
  if (val?.length == 1) {
    initParams.value.condition.whiteListProvince = val[0];
    initParams.value.condition.whiteListCity = null;
  } else if (val?.length == 2) {
    initParams.value.condition.whiteListProvince = val[0];
    initParams.value.condition.whiteListCity = val[1];
  } else {
    initParams.value.condition.whiteListProvince = null;
    initParams.value.condition.whiteListCity = null;
  }
  init("search");
};


/* 初始化数据 */
const init = async (type: string) => {
  if (type == "reset") {
    initParams.value.condition = {};
    cityCode.value = [];
    initParams.value.pageNum = 1;
    initParams.value.pageSize = 20;
    onlyTableRef.value.initPagination()
  }
  pageParams.loadIng = true;
  getProductCnfList(initParams.value).then((res) => {
    pageParams.loadIng = false;
    let {
      data: { records, total },
    } = res;
    pageParams.tableData = records.map((item:any)=>{
      return{
        ...item,
        isp:isIsp.value[item.isp]
      }
    })
    pageParams.total = total;
  });
};

/*分页*/
const handPage = async (params: any) => {
  if (params) {
    initParams.value.pageNum = params.pageNum;
    initParams.value.pageSize = params.pageSize;
  }
  init("search");
};

const handBtnClick = (item: any, data: any) => {
  if (item.type == "search") {
    initParams.value.condition = data;
    initCompPag();
    init();
  } else if (item.type == "reSet") {
    initParams.value.condition = {};
    formRef.value?.resetForm();
    initCompPag();
    init();
  } else if (item.type == "add") {
    addRef.value?.handShow();
  } else if (item.type == "upload") {
  }
};

const handTableRow = async (btn: any, row: any) => {
  if (btn.name == "删除") {
    const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.productName}`);
    if (flag) {
      delCnfPeoduct({ id: row.id }).then((res) => {
        if (res.code == 20000) {
          ElMessage({
            type: "success",
            message: "数据删除成功",
          });
          init("search");
        }
      }).catch(error => {
        ElMessage({
          type: "error",
          message: "数据删除失败",
        });
      });

    }
  } else if (btn.name == "详情") {
    getCnfProductInfo({ id: row.id }).then((res) => {
      let { data } = res;
      infoData.value = data;
      addRef.value?.handShow(true);
    });
  } else if (btn.name == "编辑") {
    getCnfProductInfo({ id: row.id }).then((res) => {
      let { data } = res;
      infoData.value = data;
      addRef.value?.handShow("", 2);
    });
  }
};
const tableFlush = (type:string) => {
  if(type=='reset'){

    init("reset");
  }else{
    init('search')
  }
};
</script>

<style lang="scss" scope>
.first_chain_view {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;
    // height: 100%;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>
